package mapper

import (
	"bytes"
	"fmt"
	"go-zero-project/services/user/rpc/internal/mapper/bo"
	"go-zero-project/services/user/rpc/internal/mapper/entity"
	"gorm.io/gorm"
)

const roleMenuSqlColumn = "id,role_id,menu_id"

type RoleMenuMapper struct {
}

func NewRoleMenuMapper() *RoleMenuMapper {
	return &RoleMenuMapper{}
}

func (mapper *RoleMenuMapper) SelectOne(db *gorm.DB, bo bo.SysRoleMenuBO) (entity.SysRoleMenuEntity, error) {
	tx := db.Session(&gorm.Session{SkipDefaultTransaction: true})
	whereSql := mapper.getAllWhereSql(bo)
	var user entity.SysRoleMenuEntity
	tx = tx.Select(roleMenuSqlColumn).Where(whereSql.String()).First(&user)
	return user, tx.Error
}

func (mapper *RoleMenuMapper) SelectCount(db *gorm.DB, bo bo.SysRoleMenuBO) (int64, error) {
	tx := db.Session(&gorm.Session{SkipDefaultTransaction: true})
	whereSql := mapper.getAllWhereSql(bo)
	var total int64
	userEntity := entity.SysUserEntity{}
	tx = tx.Select(roleMenuSqlColumn).Table(userEntity.TableName()).Where(whereSql.String()).Count(&total)
	return total, tx.Error
}

func (mapper *RoleMenuMapper) SelectList(db *gorm.DB, bo bo.SysRoleMenuBO) ([]entity.SysRoleMenuEntity, error) {
	tx := db.Session(&gorm.Session{SkipDefaultTransaction: true})
	whereSql := mapper.getAllWhereSql(bo)
	var retList []entity.SysRoleMenuEntity
	if bo.PageSize > 0 {
		// 查询语句
		tx = tx.Select(roleMenuSqlColumn).Where(whereSql.String()).Offset(bo.StartIndex).Limit(bo.PageSize).Find(&retList)
	} else {
		// 查询语句
		tx = tx.Select(roleMenuSqlColumn).Where(whereSql.String()).Find(&retList)
	}
	return retList, tx.Error
}

func (mapper *RoleMenuMapper) getAllWhereSql(roleBO bo.SysRoleMenuBO) bytes.Buffer {
	var whereSql bytes.Buffer
	whereSql.WriteString(defaultWhere)
	if roleBO.Id > 0 {
		whereSql.WriteString(fmt.Sprintf(" and dept_id =%d", roleBO.Id))
	}
	if roleBO.RoleId.Int64 > 0 {
		whereSql.WriteString(fmt.Sprintf(" and role_id =%d", roleBO.RoleId.Int64))
	}
	if roleBO.MenuId.Int64 > 0 {
		whereSql.WriteString(fmt.Sprintf(" and  menu_id=%d", roleBO.MenuId.Int64))
	}
	return whereSql
}

func (mapper *RoleMenuMapper) DeleteRoleMenu(db *gorm.DB, roleIdArr []int64) error {
	if len(roleIdArr) < 1 {
		return nil
	}
	tx := db.Where("role_id in ?", roleIdArr).Delete(&entity.SysRoleMenuEntity{})
	return tx.Error
}

func (mapper *RoleMenuMapper) BatchInsert(db *gorm.DB, entityArr []entity.SysRoleMenuEntity) ([]int64, error) {
	tx := db.Create(&entityArr)
	var idArr []int64
	for _, v := range entityArr {
		idArr = append(idArr, v.Id)
	}
	return idArr, tx.Error
}
